package yunquan.wang.jbpm5.web;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class JdbcUtils {
	
	
	public static Map<String,Object> getSingle(String sql,Object ... param)
	{
		 List<Map<String,Object>> result=query(sql, param);
		 if(result.size()==0)
		 {
			 throw new RuntimeException("查询没有结果：sql为：");
		 }
		return  result.get(0);
	}
	
	public static  List<Map<String,Object>> query(String sql,Object ... param)
	{
		 
		List<Map<String,Object>> result=new ArrayList<Map<String,Object>>();
		try {
		Connection conn= getDbConnection();
			PreparedStatement pstmt = conn.prepareStatement(sql);
			if(param!=null)	{
			for(int i=0;i<param.length;i++)
			{
				pstmt.setObject(i, param[i]);}
			}
			 if(checkIsUpdate(sql)){ pstmt.executeUpdate();
			 }
			 else
			 {
			ResultSet res=		pstmt.executeQuery();
			while(res.next()){
				//获取查询结果的元数据，做到此查询通用
				ResultSetMetaData meta=	res.getMetaData();
				int columnSize=meta.getColumnCount();
				Map<String,Object> row=new HashMap<String,Object>();
				for(int i=0;i<columnSize;i++){
				String columnName=	meta.getColumnName(i+1);
				row.put(columnName, res.getObject(columnName));
				}
				result.add(row);
			}
				res.close();
				res=null;
			}	
				pstmt.close();
				conn.close();
				pstmt=null;
				conn=null;
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return result;
	}
	
	
	private static Connection getDbConnection()
	{
	   String url = "jdbc:mysql://localhost/sunyard?useUnicode=true&characterEncoding=utf-8" ;    
	     String username = "root" ;   
	     String password = "741369" ;   
	     try{   
	    	 Class.forName("com.mysql.jdbc.Driver") ;  
	    Connection con = DriverManager.getConnection(url , username , password ) ;   
	    return con;
	     }catch(Exception se){   
	    se.printStackTrace() ;   
	     } 
	 	return null;
	}

/**
 * 检查是否是更新或修改
 * @param sql
 * @return
 */
	public static boolean checkIsUpdate(String sql)
	{
		sql=sql.toUpperCase();
		if(sql.contains("INSERT")||sql.contains("UPDATE")||sql.contains("DELETE"))
			return true;
		else
			return false;
	}
	
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		 try {
			System.out.println(query(" INSERT INTO a_user (NAME,groupid) VALUES ('22','33')"));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
}
